<?php
namespace app\service;

use support\Redis;
use Webman\Event\Event;
use Webman\RedisQueue\Client;
use const support\AUTO_HANDLE_ORDER_REFUND_QUEUE;
use const support\order_refund_auto_handle_interval;
use const support\SEND_SMS_QUEUE;
use const support\SMS_DEFAULT_CODE;
use const support\SMS_DEFAULT_WHITE_LISTS;
use const support\SMS_SCENE_CODE;
use const support\SMS_SCENE_EXPIRE_TIME;

class SmsService{

    /**
     * 获取短信验证码
     * @param int $scene
     * @param string $mobile
     * @return bool|string
     */
    public static function getSmsCode(int $scene,string $mobile){
        //拼装验证码缓存标识
        $cache=sprintf(SMS_SCENE_CODE,$mobile,$scene);
        //检测验证码在缓存中的状态
        $code=Redis::get($cache);
        if (!$code){
            return false;
        }
        return $code;
    }

    /**
     * 移除短信验证码
     * @param int $scene
     * @param string $mobile
     * @return int
     */
    public static function removeSmsCode(int $scene,string $mobile): int
    {
        //拼装验证码缓存标识
        $cache=sprintf(SMS_SCENE_CODE,$mobile,$scene);
        return Redis::del($cache);
    }

    /**
     * 短信验证码发送
     * @param int $scene
     * @param string $mobile
     * @return int|string
     */
    public static function sendSmsCode(int $scene,string $mobile){
        //拼装验证码缓存标识
        $cache=sprintf(SMS_SCENE_CODE,$mobile,$scene);
        //生成验证码
        $code=rand_string(4,'0123456789');
        //检测是否命中白名单或者环境是否正式
        if (!checkRuntimeEnv() || in_array($mobile,SMS_DEFAULT_WHITE_LISTS)){
            $code=SMS_DEFAULT_CODE;
        }else{
            //调用运营商发送短信
//            Event::emit('sms.sendCode', [
//                'mobile'=>$mobile,
//                'code'  =>$code
//            ]);
            Client::send(SEND_SMS_QUEUE, [
                'mobile'=>$mobile,
                'code'  =>$code
            ]);
        }
        //将验证码存储缓存
        Redis::setEx($cache,SMS_SCENE_EXPIRE_TIME,$code);
        return $code;
    }


}